package mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * Created by 10188 on 2018/3/28.
 */
public class InnerApp {

    private String messageStr;
    private String topicStrRes="BFEBFBFF000306C3/device/rsp";

    private String userName = "admin";
    private String passWord = "password";

    private static String host="tcp://192.168.31.141:1883";
    private static String clientId = "innerApp";

    private MqttClient client;



    public static void main(String[] args) throws MqttException {


        new InnerApp().myclient();
    }

    public void myclient() throws MqttException {
        client = new MqttClient(host, clientId, new MemoryPersistence());
        //与activeMQ连接的方法
        connect();
    }
    private void connect() {
        // new mqttConnection 用来设置一些连接的属性
        MqttConnectOptions options = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
        // 换而言之，设置为false时可以客户端可以接受离线消息
        options.setCleanSession(false);
        // 设置超时时间
        options.setConnectionTimeout(10);

        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);
        try {
            // 设置回调类
            client.setCallback(new MqttCallback(){
                public void connectionLost(Throwable arg0) {
                    System.out.println("mqtt connection lost");
                }

                public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                    String msg = new String(mqttMessage.getPayload());
                    System.out.println(msg);
                }

                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    System.out.println("deliveryComplete:" + iMqttDeliveryToken.getMessageId());
                }
            });
            // 连接
            client.connect(options);
            client.subscribe(topicStrRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
